#!/bin/bash

# ============================================
# 快速部署前端到 Nginx
# ============================================

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

echo_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

echo_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

echo_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

echo_step() {
    echo -e "${BLUE}[STEP]${NC} $1"
}

# 检查是否为 root
if [ "$EUID" -ne 0 ]; then
    echo_error "请使用 sudo 运行此脚本"
    exit 1
fi

echo_info "============================================"
echo_info "前端快速部署脚本"
echo_info "============================================"
echo ""

# 配置变量
DIST_PATH="/root/OCR_CER_AUIDT_ADMIN/django-vue3-admin/web/dist"
DEPLOY_PATH="/var/www/frontend"
NGINX_CONF="/etc/nginx/conf.d/frontend.conf"
BACKEND_API="http://10.170.129.4:8000"

# 步骤 1: 检查 dist 目录是否存在
echo_step "步骤 1: 检查 dist 目录..."
if [ ! -d "$DIST_PATH" ]; then
    echo_error "dist 目录不存在: $DIST_PATH"
    echo_info "请先确认 dist 目录路径，或手动指定："
    read -p "输入 dist 目录的完整路径: " DIST_PATH
    if [ ! -d "$DIST_PATH" ]; then
        echo_error "路径不存在: $DIST_PATH"
        exit 1
    fi
fi

echo_info "✓ 找到 dist 目录: $DIST_PATH"
ls -lh "$DIST_PATH" | head -5
echo ""

# 步骤 2: 创建部署目录
echo_step "步骤 2: 创建部署目录..."
mkdir -p "$DEPLOY_PATH"
chown -R root:root "$DEPLOY_PATH"
chmod -R 755 "$DEPLOY_PATH"
echo_info "✓ 部署目录已创建: $DEPLOY_PATH"
echo ""

# 步骤 3: 复制文件
echo_step "步骤 3: 复制 dist 文件到部署目录..."
echo_info "从: $DIST_PATH"
echo_info "到: $DEPLOY_PATH"
cp -r "$DIST_PATH"/* "$DEPLOY_PATH"/
echo_info "✓ 文件复制完成"
echo ""

# 验证文件
echo_info "验证部署目录内容："
ls -lh "$DEPLOY_PATH" | head -10
echo ""

# 步骤 4: 配置 Nginx
echo_step "步骤 4: 配置 Nginx..."

# 检查是否已有配置文件
if [ -f "$NGINX_CONF" ]; then
    echo_warn "配置文件已存在: $NGINX_CONF"
    read -p "是否覆盖现有配置？(y/N): " overwrite
    if [[ ! $overwrite =~ ^[Yy]$ ]]; then
        echo_info "跳过配置文件创建，使用现有配置"
    else
        echo_info "备份现有配置..."
        cp "$NGINX_CONF" "${NGINX_CONF}.backup.$(date +%Y%m%d_%H%M%S)"
        echo_info "创建新配置..."
        cat > "$NGINX_CONF" << EOF
server {
    listen 80;
    server_name 10.170.129.4;
    
    # 前端静态文件目录
    root $DEPLOY_PATH;
    index index.html;
    
    # 日志配置
    access_log /var/log/nginx/frontend_access.log;
    error_log /var/log/nginx/frontend_error.log;
    
    # 客户端上传文件大小限制
    client_max_body_size 100M;
    
    # Gzip 压缩配置
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_comp_level 6;
    gzip_types 
        text/plain 
        text/css 
        text/xml 
        text/javascript 
        application/json 
        application/javascript 
        application/x-javascript 
        application/xml+rss 
        application/xhtml+xml 
        image/svg+xml;
    
    # 前端路由配置（Vue Router History 模式）
    location / {
        try_files \$uri \$uri/ /index.html;
        
        # 禁止缓存 HTML 文件
        if (\$request_uri ~* "^/\$|^/index.html|^/index.htm") {
            add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate";
            add_header Pragma "no-cache";
            expires -1;
        }
        
        # 静态资源缓存
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot|otf)$ {
            expires 7d;
            add_header Cache-Control "public, immutable";
            access_log off;
        }
    }
    
    # API 代理配置（代理到 Django 后端）
    location /api/ {
        proxy_pass $BACKEND_API/api/;
        proxy_http_version 1.1;
        
        # 请求头设置
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_set_header X-Nginx-Proxy true;
        
        # WebSocket 支持
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        
        # 超时设置
        proxy_connect_timeout 600s;
        proxy_read_timeout 600s;
        proxy_send_timeout 600s;
        
        # 缓冲区设置
        proxy_buffering off;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
        
        # 文件上传大小限制
        client_max_body_size 100M;
    }
    
    # 禁止访问隐藏文件
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }
}
EOF
        echo_info "✓ Nginx 配置已创建"
    fi
else
    echo_info "创建 Nginx 配置文件..."
    cat > "$NGINX_CONF" << EOF
server {
    listen 80;
    server_name 10.170.129.4;
    
    # 前端静态文件目录
    root $DEPLOY_PATH;
    index index.html;
    
    # 日志配置
    access_log /var/log/nginx/frontend_access.log;
    error_log /var/log/nginx/frontend_error.log;
    
    # 客户端上传文件大小限制
    client_max_body_size 100M;
    
    # Gzip 压缩配置
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_comp_level 6;
    gzip_types 
        text/plain 
        text/css 
        text/xml 
        text/javascript 
        application/json 
        application/javascript 
        application/x-javascript 
        application/xml+rss 
        application/xhtml+xml 
        image/svg+xml;
    
    # 前端路由配置（Vue Router History 模式）
    location / {
        try_files \$uri \$uri/ /index.html;
        
        # 禁止缓存 HTML 文件
        if (\$request_uri ~* "^/\$|^/index.html|^/index.htm") {
            add_header Cache-Control "no-store, no-cache, must-revalidate, proxy-revalidate";
            add_header Pragma "no-cache";
            expires -1;
        }
        
        # 静态资源缓存
        location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot|otf)$ {
            expires 7d;
            add_header Cache-Control "public, immutable";
            access_log off;
        }
    }
    
    # API 代理配置（代理到 Django 后端）
    location /api/ {
        proxy_pass $BACKEND_API/api/;
        proxy_http_version 1.1;
        
        # 请求头设置
        proxy_set_header Host \$host;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
        proxy_set_header X-Nginx-Proxy true;
        
        # WebSocket 支持
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection "upgrade";
        
        # 超时设置
        proxy_connect_timeout 600s;
        proxy_read_timeout 600s;
        proxy_send_timeout 600s;
        
        # 缓冲区设置
        proxy_buffering off;
        proxy_buffer_size 4k;
        proxy_buffers 8 4k;
        
        # 文件上传大小限制
        client_max_body_size 100M;
    }
    
    # 禁止访问隐藏文件
    location ~ /\. {
        deny all;
        access_log off;
        log_not_found off;
    }
}
EOF
    echo_info "✓ Nginx 配置已创建"
fi

echo ""

# 步骤 5: 测试 Nginx 配置
echo_step "步骤 5: 测试 Nginx 配置..."
if nginx -t; then
    echo_info "✓ Nginx 配置测试通过"
else
    echo_error "Nginx 配置测试失败！"
    exit 1
fi
echo ""

# 步骤 6: 重启 Nginx
echo_step "步骤 6: 重启 Nginx 服务..."
systemctl reload nginx || systemctl restart nginx
if systemctl is-active --quiet nginx; then
    echo_info "✓ Nginx 重启成功"
else
    echo_error "Nginx 重启失败！"
    systemctl status nginx --no-pager
    exit 1
fi
echo ""

# 步骤 7: 显示部署信息
echo_info "============================================"
echo_info "部署完成！"
echo_info "============================================"
echo_info "前端文件目录: $DEPLOY_PATH"
echo_info "Nginx 配置文件: $NGINX_CONF"
echo_info "后端 API 地址: $BACKEND_API"
echo_info ""
echo_info "访问地址:"
echo_info "  - HTTP: http://10.170.129.4"
echo_info ""
echo_info "检查服务状态:"
echo_info "  sudo systemctl status nginx"
echo_info ""
echo_info "查看日志:"
echo_info "  sudo tail -f /var/log/nginx/frontend_access.log"
echo_info "  sudo tail -f /var/log/nginx/frontend_error.log"
echo_info ""
echo_info "测试配置:"
echo_info "  sudo nginx -t"
echo_info "============================================"

